package com.bawei.shopping.fragment

import android.content.Context
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.activity.viewModels
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import com.bawei.shopping2.R
import com.bawei.shopping2.databinding.FragmentTwoBinding
import com.bawei.shopping2.entity.BannerEntity
import com.bawei.shopping2.http.ApiResponse
import com.bawei.shopping2.utils.GlideUtils
import com.bawei.shopping2.viewmodel.MainViewModel
import com.youth.banner.BannerConfig
import com.youth.banner.Transformer
import com.youth.banner.loader.ImageLoader
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch

@AndroidEntryPoint
class TwoFragment : Fragment() {
    private val mainViewModel: MainViewModel by activityViewModels()
    private var  job = Job() //协程任务
    private lateinit var fragmentTwoBinding: FragmentTwoBinding
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        fragmentTwoBinding = FragmentTwoBinding.inflate(inflater,container,false)
        //使用协程请求数据展示数据
        CoroutineScope(job).launch(Dispatchers.Main) {
            var apiResponse =  mainViewModel.banners()//耗时操作，因为retorfit默认在子线程中
            showBanner(apiResponse)//展示UI
        }
        return fragmentTwoBinding.root
    }

    fun showBanner(apiResponse: ApiResponse<MutableList<BannerEntity>>){
        if(apiResponse.code == 200){
            var images = mutableListOf<String>()
            var titles = mutableListOf<String>()
            apiResponse.data.forEach {
                images.add(it.imagePath)
                titles.add(it.desc)
            }
            fragmentTwoBinding.banner.let {
                it.setBannerTitles(titles)//设置标题
                it.setImages(images)//设置图图片
                it.setBannerStyle(BannerConfig.NUM_INDICATOR_TITLE)//设置类型：标题+数字
                it.setImageLoader(object : ImageLoader() {//设置图片加载器
                override fun displayImage(
                    context: Context?,
                    path: Any?,
                    imageView: ImageView?
                ) {
                    GlideUtils.loadNormal(context,imageView, path as String?)
                }

                })
                it.setBannerAnimation(Transformer.FlipHorizontal)//设置动画
                it.start()//启动
            }
        }




    }

    //页面销毁取消协程任务
    override fun onDestroy() {
        super.onDestroy()
        job.cancel()
    }


}